package com.leo.javase.thread.itcast;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {

	public static void main(String[] args) {
		new LockTest().init();
	}
	/**
	 * leolyi
	 * 
	 */
	public void init(){
		final Outputer out = new Outputer();
		new Thread(new Runnable(){
			public void run() {
				while(true){
					/*try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}*/
					out.output("leolian");
				}
			}
		}).start();
		new Thread(new Runnable(){
			public void run() {
				while(true){
					/*try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}*/
					out.output("nieyi");
				}
			}
		}).start();
	}
	
	/**
	 * 内部类
	 * @author Lian
	 */
	static class Outputer{
		Lock lock = new ReentrantLock();
		
		public void output(String name){
			int i = name.length();
			
			lock.lock();
			try{
				for(int j=0; j<i; j++){
					System.out.print(name.charAt(j));
				}
				System.out.println();
				
				//抛出异常
				int res = 1/0;
			}catch(Exception e){
				System.out.println("有异常了，释放锁");
			}finally{
				lock.unlock();
			}
			
		}
	}
	
}
